package com.justgame.project.mq.consumer.system;

import com.alibaba.fastjson.JSONObject;
import com.justgame.mq.client.constant.SystemQueueConstant;
import com.justgame.project.cloud.common.util.RabbitHelper;
import com.justgame.project.service.system.entity.SysUserInfo;
import com.justgame.project.service.system.feign.ISysUserInfoClient;
import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 接收来自System模块的消息队列
 *
 * @author ZhouWeiBo
 * @create 2022/5/10
 */
@Slf4j
@Component
@AllArgsConstructor
public class UserLoginConsumer extends RabbitHelper{
    private final ISysUserInfoClient sysUserInfoClient;

    /**
     * 处理用户登陆后续
     */
    @RabbitHandler
    @RabbitListener(queues = SystemQueueConstant.SYSTEM_USER_LOGIN_QUEUE)
    public void processUserLogin(Channel channel, Message message) throws IOException {
        try {
            String msgText = new String(message.getBody());
            log.info(msgText);
            SysUserInfo userInfo = JSONObject.parseObject(msgText, SysUserInfo.class);
            log.info("UserId【{}】：已登录，正在处理后续业务...", userInfo.getId());
            /* 更新最后登录日期为此时 */
            userInfo.setLastAccessDate(LocalDateTime.now());
            sysUserInfoClient.updateById(userInfo);
            log.info("UserId【{}】：登录后续业务处理完毕！", userInfo.getId());
            execute(message);
        } catch (Exception e) {
            e.printStackTrace();
            receive(message,e);
        } finally {
            // ACK
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
